package com.goudan.practice.tree;

/**
 * 满二叉树
 *
 * - 如何判断一棵树是满二叉树
 * - 树最大深度L，节点个数N，满足N=2(L次方)-1
 * - 解法：先求二叉树最大深度L，再求节点个数N，满足N=2(L次方)-1
 */
public class FullTree {
    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    /**
     * 返回值信息
     */
    public static class Info {
        public int height;
        public int nodes;

        public Info(int h, int n) {
            height = h;
            nodes = n;
        }
    }

    public static void main(String[] args) {

    }


    public static boolean isFull(Node head) {
        if (head == null) {
            return true;
        }
        Info all = process(head);
        // N=2(L次方)-1
        return (1 << all.height) - 1 == all.nodes;
    }

    public static Info process(Node head) {
        if (head == null) {
            return new Info(0, 0);
        }
        Info leftInfo = process(head.left);
        Info rightInfo = process(head.right);
        // 高度等于左树和右树最高的高度+1
        int height = Math.max(leftInfo.height, rightInfo.height) + 1;
        // 总个数等于左边的个数加上右边的个数加1
        int nodes = leftInfo.nodes + rightInfo.nodes + 1;
        return new Info(height, nodes);
    }


}
